package com.kandinfo.base.admin.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.kandinfo.base.admin.domain.ScheduleJob;
import com.kandinfo.base.admin.dto.ScheduleJobDto;
import com.kandinfo.base.admin.dto.ScheduleJobSearchDto;
import com.kandinfo.base.common.repository.AliasToBeanResultTransformerEx;

@Repository
public class ScheduleJobSearchRepository {
    
	@Autowired
	private EntityManager entityManager;
	
    @SuppressWarnings("unchecked")
	public List<ScheduleJobDto> searchByCon(ScheduleJobSearchDto searchDto){
        StringBuffer sb = new StringBuffer("select id as jobId,job_name as jobName,job_group as jobGroup,job_status as jobStatus"
        		+ ",cron_expression as cronExpression,description,bean_class as beanClass,"
                + "is_concurrent as isConcurrent,spring_id as springId,method_name as methodName"
                + ",create_ts as createTime,update_ts as updateTime from quartz_job");
        sb.append(getSearchSql(searchDto));
        
        Query nativeQuery = entityManager.createNativeQuery(sb.toString());
        org.hibernate.Query query = nativeQuery.unwrap(org.hibernate.Query.class);
        query.setResultTransformer(new AliasToBeanResultTransformerEx(ScheduleJobDto.class));
        return query.list();
    }
    
    public Long getScheduleJobListCount(ScheduleJobSearchDto searchDto){
        StringBuffer sb = new StringBuffer("select count(1) c from quartz_job ");
        sb.append(getSearchSql(searchDto));
        
        Query nativeQuery = entityManager.createNativeQuery(sb.toString());
        return Long.valueOf(nativeQuery.getResultList().size());
        
    }
    
    public String getSearchSql(ScheduleJobSearchDto searchDto){
        StringBuffer sb = new StringBuffer();
        sb.append(" where 1=1 ");
        if(StringUtils.isNotBlank(searchDto.getJobName())){
            sb.append(" and job_name like '%"+searchDto.getJobName()+"%'");
        }
        return sb.toString();
    }
    
    @SuppressWarnings("unchecked")
	public List<ScheduleJob> getAll(){
    	 StringBuffer sb = new StringBuffer("select id as jobId,job_name as jobName,job_group as jobGroup,job_status as jobStatus"
         		+ ",cron_expression as cronExpression,description,bean_class as beanClass,"
                 + "is_concurrent as isConcurrent,spring_id as springId,method_name as methodName"
                 + ",create_ts as createTime,update_ts as updateTime from quartz_job");
        
        Query nativeQuery = entityManager.createNativeQuery(sb.toString());
        org.hibernate.Query query = nativeQuery.unwrap(org.hibernate.Query.class);
        query.setResultTransformer(new AliasToBeanResultTransformerEx(ScheduleJob.class));
        return query.list();
        
    }
    
    /*public ScheduleJob getJobById(Long JobId){
    	 StringBuffer sb = new StringBuffer("select id as jobId,job_name as jobName,job_group as jobGroup,job_status as jobStatus"
          		+ ",cron_expression as cronExpression,description,bean_class as beanClass,"
                  + "is_concurrent as isConcurrent,spring_id as springId,method_name as methodName"
                  + ",create_ts as createTime,update_ts as updateTime from quartz_job");
    	 
        DBUtil db = new DBUtil(0);
        String sql = "select jobId,jobName,jobGroup,jobStatus,cronExpression,description,beanClass,"
                + "isConcurrent,springId,methodName,createTime,updateTime from quartz_job where 1=1 and jobId = ?";
        String[] args = new String[]{JobId+""};
        try {
            ResultSet rs = db.exeQuery(sql, args);
            while(rs.next()){
                ScheduleJob sch = new ScheduleJob();
                sch.setJobId(rs.getLong("jobId"));
                sch.setJobName(rs.getString("jobName"));
                sch.setJobGroup(rs.getString("jobGroup"));
                sch.setJobStatus(rs.getString("jobStatus"));
                sch.setCronExpression(rs.getString("cronExpression"));
                sch.setDescription(rs.getString("description"));
                sch.setBeanClass(rs.getString("beanClass"));
                sch.setIsConcurrent(rs.getString("isConcurrent"));
                sch.setSpringId(rs.getString("springId"));
                sch.setMethodName(rs.getString("methodName"));
                sch.setCreateTime(rs.getDate("createTime"));
                sch.setUpdateTime(rs.getDate("updateTime"));
                return sch;
            }
        } catch (SQLException e) {
            throw new BaseException(EErrorCode.SQL_EXCEPTION);
        }finally{
            db.releaseConnection();
        }
        return null;
    }
    
    public void deletejob(List<Long> jobIds){
        DBUtil db = new DBUtil(0);
        String sql = "delete from quartz_job where jobId in (?)";
        String[] args = new String[]{jobIds.size()>0?jobIds.toString().replace("[", "").replace("]", ""):"-1"};
        try {
            db.exeUpdate(sql, args);
        } catch (SQLException e) {
            throw new BaseException(EErrorCode.SQL_EXCEPTION);
        }finally{
            db.releaseConnection();
        }
    }
    
    *//**
     * 
    * Description: TODO
    *
    * @param job
     *//*
    public Integer insertJob(ScheduleJob job){
        DBUtil db = new DBUtil(0);
        String sql = "insert into quartz_job(jobName,jobGroup,jobStatus,cronExpression,description,beanClass,springId,methodName,createTime,isConcurrent) value(?,?,'0',?,?,?,?,?,now(),'0')";
        String[] args = new String[]{job.getJobName(),job.getJobGroup(),job.getCronExpression(),job.getDescription(),job.getBeanClass(),
                job.getSpringId(),job.getMethodName()};
        try {
            return db.exeUpdate(sql, args);
        } catch (SQLException e) {
            throw new BaseException(EErrorCode.SQL_EXCEPTION);
        }finally{
            db.releaseConnection();
        }
    }
    
    *//**
     * 
    * Description: 
    *
    * @param job
     *//*
    public Integer updateById(ScheduleJob job){
        DBUtil db = new DBUtil(0);
        StringBuffer sb = new StringBuffer("update quartz_job set jobName=?,jobGroup=?,cronExpression=?,"
                + "description=?,beanClass=?,springId=?,updateTime=now(),methodName=? where jobId = ?");
        String[] args = new String[]{job.getJobName(),job.getJobGroup(),job.getCronExpression(),
                job.getDescription(),job.getBeanClass(),job.getSpringId(),job.getMethodName(),job.getJobId()+""};
        try {
            Integer id = db.exeUpdate(sb.toString(), args);
            return id;
        } catch (SQLException e) {
            throw new BaseException(EErrorCode.SQL_EXCEPTION);
        }finally{
            db.releaseConnection();
        }
    }
    
    *//**
     * 
    * Description: 
    *
    * @param JobId
    * @param jobstatus
     *//*
    public void updateStatusByJobId(Long JobId,String jobstatus){
        DBUtil db = new DBUtil(0);
        String sql = "update quartz_job set jobStatus = ? where jobId = ?";
        String[] args = new String[]{jobstatus,JobId+""};
        try {
            db.exeUpdate(sql, args);
        } catch (SQLException e) {
            throw new BaseException(EErrorCode.SQL_EXCEPTION);
        }finally{
            db.releaseConnection();
        }
    }*/
}
